package cn.edu.henu.team.fragments;

import android.content.Intent;
import android.view.View;
import android.view.ViewTreeObserver;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ScrollView;
import android.widget.TextView;

import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.lzy.imagepicker.bean.ImageItem;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.scwang.smart.refresh.footer.ClassicsFooter;
import com.scwang.smart.refresh.header.ClassicsHeader;
import com.scwang.smart.refresh.layout.SmartRefreshLayout;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnLoadMoreListener;
import com.scwang.smart.refresh.layout.listener.OnRefreshListener;

import java.util.ArrayList;
import java.util.List;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.BmobUser;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.FindListener;
import cn.edu.henu.team.R;
import cn.edu.henu.team.adapter.Frag3RecyclerAdapter;
import cn.edu.henu.team.adapter.MyAdapter;
import cn.edu.henu.team.base.BaseFragment;
import cn.edu.henu.team.bean.Post1;
import cn.edu.henu.team.ui.CommentActivity;
import cn.edu.henu.team.ui.FuActivity;
import cn.edu.henu.team.ui.SortCityActivity;
import cn.edu.henu.team.ui.PbProblemActivity;
import cn.edu.henu.team.ui.SearchActivity;
import cn.edu.henu.team.utils.MyListview;

import static cn.bmob.v3.Bmob.getApplicationContext;

public class fragment3 extends BaseFragment {
    private int count=0,num=10;
    private fragment3 mContext;
    private SmartRefreshLayout refreshSrl;
    private ScrollView scrollView;
    private Button search;
    private ImageView sortCity;
    private ImageView problem;

    private MyAdapter adapter1;
    private List<Post1> list = new ArrayList<>();
    private MyListview lv;

    private AlertDialog al;
    private String headUrl = "";
    private ArrayList<ImageItem> imageItems;
    private BmobUser user;
    private String head_url_res = "";//获得后的头像url
    private String post_obj = "123";//查询帖子用户obiId
    private String post_head = "1234";//查询帖子用户头像地址url

    // 热门内容板块
    private List<Integer> data = new ArrayList<>();//必须初始化
    private RecyclerView recyclerView;
    private Frag3RecyclerAdapter adapter;

    private TextView fu;

    private DisplayImageOptions options; // 设置图片显示相关参数

    public static fragment3 newInstance() {
        fragment3 fragment = new fragment3();
        return fragment;
    }

    @Override
    protected int initLayout() {
        return R.layout.fragment_3;
    }

    @Override
    protected void initView() {
        mContext = fragment3.this;

        refreshSrl=mRootView.findViewById(R.id.refresh_srl);
        refreshSrl.setRefreshHeader(new ClassicsHeader(getApplicationContext()));
        refreshSrl.setRefreshFooter(new ClassicsFooter(getApplicationContext()));

        refreshSrl.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                refreshSrl.finishRefresh(1000/*,false*/);
                initData();
            }
        });

        refreshSrl.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(RefreshLayout refreshlayout) {
                refreshlayout.finishLoadMore(1000/*,false*/);//传入false表示加载失败
            }
        });

        recyclerView = mRootView.findViewById(R.id.recyclerview);

        search = mRootView.findViewById(R.id.search_button3);
        fu = mRootView.findViewById(R.id.fu);
        sortCity = mRootView.findViewById(R.id.sortCity);
        problem = mRootView.findViewById(R.id.problem);
        lv = mRootView.findViewById(R.id.lv);
        user = BmobUser.getCurrentUser();

        // 使用DisplayImageOptions.Builder()创建DisplayImageOptions
        options = new DisplayImageOptions.Builder()
                .showImageOnLoading(R.mipmap.upload) // 设置图片下载期间显示的图片
                .showImageForEmptyUri(R.mipmap.upload) // 设置图片Uri为空或是错误的时候显示的图片
                .showImageOnFail(R.mipmap.upload) // 设置图片加载或解码过程中发生错误显示的图片
                .cacheInMemory(true) // 设置下载的图片是否缓存在内存中
                .cacheOnDisk(true) // 设置下载的图片是否缓存在SD卡中
                .build(); // 构建完成

        scrollView = mRootView.findViewById(R.id.scroll);
        if (scrollView != null) {
            scrollView.getViewTreeObserver().addOnScrollChangedListener(new ViewTreeObserver.OnScrollChangedListener() {
                @Override
                public void onScrollChanged() {
                }
            });
        }
    }

    @Override
    protected void initData() {
        if(data.size()!=0)
            data.clear();
        if(list.size()!=0)
            list.clear();
        // 热门内容板块
        LinearLayoutManager layoutManager = new LinearLayoutManager(getApplicationContext());
        layoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
        recyclerView.setLayoutManager(layoutManager);
        data.add(R.mipmap.frag3_user);
        data.add(R.mipmap.frag3_blog);
        data.add(R.mipmap.frag3_book);
        adapter = new Frag3RecyclerAdapter(data);
        recyclerView.setAdapter(adapter);
        adapter1 = new MyAdapter(getActivity(), list);
        lv.setAdapter(adapter1);

        BmobQuery<Post1> query = new BmobQuery<Post1>();
        query.order("-createdAt");
        query.setLimit(20);
        query.findObjects(new FindListener<Post1>() {
            @Override
            public void done(List<Post1> lists, BmobException e) {
                if (e == null) {
                    list = lists;
                    adapter1.addPost(list);
                    adapter1.notifyDataSetChanged();
                }
            }
        });
    }

    @Override
    protected void clickEvents() {
        search.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent it = new Intent(getActivity(), SearchActivity.class);
                startActivity(it);
            }
        });

        sortCity.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(getActivity(), SortCityActivity.class));
            }
        });

        problem.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(getActivity(), PbProblemActivity.class));
            }
        });

        lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                intentToComm(i);
            }
        });

        fu.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(getActivity(), FuActivity.class));
            }
        });
    }

    /*
     传递数据到详情页
    */
    public void intentToComm(int i){
        //传递数据到评论页面
        Intent intent = new Intent(getActivity(), CommentActivity.class);
        intent.putExtra("objectId",list.get(i).getUserID());
        intent.putExtra("username", list.get(i).getUserName());
        intent.putExtra("content", list.get(i).getContent());
        intent.putExtra("time", list.get(i).getCreatedAt());
        intent.putExtra("head", list.get(i).getUserIcon());
        Boolean isHaven=list.get(i).isHaveIcon();
        if (isHaven){
            intent.putExtra("isHaven","true");
        }else {
            intent.putExtra("isHaven","false");
        }

        String good = list.get(i).getPraise().toString();
        intent.putExtra("goods", good);

        //如果帖子没有图片就做处理 传入空
        if (list.get(i).getHeadImgUrl() != null) {
            intent.putStringArrayListExtra("infoList", (ArrayList<String>) list.get(i).getHeadImgUrl());
        } else {
            intent.putStringArrayListExtra("infoList", null);

        }
        intent.putExtra("obj", list.get(i).getObjectId());
        startActivity(intent);
    }
}
